using System;
using System.Collections.Generic;
using System.Text;
using RS.DOM.Common;

namespace RS.DOM.Construction
{
    public class DocArea
    {
        #region Constructors

        public DocArea()
        {
            this.Create(0, 0);
        }

        #endregion

        #region Members

        private DocItem[,] m_area;

        #endregion

        #region Property

        public int Width
        {
            get
            {
                return m_area.GetLength(0);
            }
        }

        public int Height
        {
            get
            {
                return m_area.GetLength(1);
            }
        }

        public bool IsEmpty
        {
            get
            {
                return (this.Width == 0 && 
                        this.Height == 0);
            }
        }

        #endregion

        #region Methods

        public void Create(int width, int height)
        {
            m_area = new DocItem[width, height];
            for (int i = 0; i < m_area.GetLength(0); i++)
                for (int j = 0; j < m_area.GetLength(1); j++)
                {
                    m_area[i, j] = new DocItem();
                    m_area[i, j].X = i;
                    m_area[i, j].Y = j;
                }
        }

        public void SetItem(int x, int y, DocItem item)
        {
            m_area[x, y] = item;
        }

        public DocItem GetItem(int x, int y)
        {
            return m_area[x, y];
        }

        public List<DocItem> Items
        {
            get
            {
                List<DocItem> items = new List<DocItem>();
                for (int i = 0; i < this.Width; i++)
                for (int j = 0; j < this.Height; j++)
                {
                    items.Add(this.GetItem(i, j));
                }

                return items;
            }
            
        }

        public override string ToString()
        {
            StringBuilder lines = new StringBuilder();
            if (!this.IsEmpty)
            {
                for (int y = 0; y < this.Height; y++)
                {
                    StringBuilder line = new StringBuilder();
                    for (int x = 0; x < this.Width; x++)
                    {
                        if (line.Length > 0)
                            line.Append(",");

                        line.Append(this.GetItem(x, y).ToString());
                    }

                    if (lines.Length > 0)
                        lines.Append("\r\n");

                    lines.Append(line);
                }
            }
            else
            {
                lines.Append("$");
            }

            return lines.ToString();
        }

        public void Clear()
        {
            this.Create(0, 0);
        }

        #endregion
    }
}
